//
//  NvFilmViewController.m
//  NvSellerShow
//
//  Created by xuewen on 2017/2/9.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvFilmViewController.h"
#import "UIColor+Hex.h"
#import "NvFilmCollectionViewCell.h"
#import "NvsLiveWindow.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "NvPlaySlider.h"
#import "Utils.h"
#import "NvFilmUploadViewController.h"
#import "MsVideoUploadModel.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface NvFilmViewController ()
{
    NSIndexPath *_selectedIndexPath;
}
@property (nonatomic, strong) UIImageView *navigationBarBottomLine;
@property (strong, nonatomic) IBOutlet UIView *filmView;
@property (strong, nonatomic) UIButton *editButton;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) NSMutableArray *sourceData;
@property (nonatomic, strong) PHFetchResult *allLocalVides;

@end

@implementation NvFilmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isEditing = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initLocalVideoData];
    [self initFilmCollectionView];
    [self initNavigationBarView];
    [self.view addSubview:self.bottomView];
    [self initCollectionViewSourceData];
}

- (void)initCollectionViewSourceData {
    _sourceData = [NSMutableArray array];
    NSString *filename = [self videoInfoFileName];
    NSArray *videoArray = [[NSArray alloc]initWithContentsOfFile:filename];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (NSDictionary *videoDict in videoArray) {
            NSURL *fileURL = [NSURL fileURLWithPath:[videoDict valueForKey:@"videoPath"]];
            if ([self hasVideoInLocalWith:fileURL]) {
                MsVideoUploadModel *uploadModel = [[MsVideoUploadModel alloc]initFromDict:videoDict];
                [_sourceData addObject:uploadModel];
                [self.filmCollectionView reloadData];
            }
        }
    });
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height_LL - 44 - 64, self.view.width_LL, 44)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.layer.masksToBounds = YES;
        [_bottomView setHidden:YES];
        
        UIButton *allSelectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        allSelectedBtn.frame = CGRectMake(25, 5, self.view.width_LL*0.4, 34);
        allSelectedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [allSelectedBtn setTitle:@"全选" forState:UIControlStateNormal];
        [allSelectedBtn addTarget:self action:@selector(doAllSelectedEvent:) forControlEvents:UIControlEventTouchUpInside];
        allSelectedBtn.backgroundColor = UIColorHexRGB(@"#3F80FF");
        [allSelectedBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        allSelectedBtn.layer.cornerRadius = 5;
        allSelectedBtn.tag = 1111;
        [_bottomView addSubview:allSelectedBtn];
        
        
        UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancleBtn.frame = CGRectMake(_bottomView.width_LL*0.6 - 25, 5, self.view.width_LL*0.4, 34);
        [cancleBtn setTitle:@"删除" forState:UIControlStateNormal];
        [cancleBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        cancleBtn.backgroundColor = UIColorHexRGB(@"#3F80FF");
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [cancleBtn addTarget:self action:@selector(doDeleteBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        cancleBtn.tag = 2222;
        cancleBtn.layer.cornerRadius = 5;
        [_bottomView addSubview:cancleBtn];
        
    }
    return _bottomView;
}

- (UIImageView *)findBottomLineUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findBottomLineUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationBarBottomLine.hidden = YES;
    self.filmView.backgroundColor = UIColorHexRGB(@"#F5F5F5");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationBarBottomLine.hidden = NO;
    [self writeDataToFile];
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backHome:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editButton.frame = CGRectMake(self.view.width_LL-40, 0, 40, 44);
    [self.editButton setTitleColor:UIColorHexRGB(@"#3F80FF") forState:UIControlStateNormal];
    self.editButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.editButton setTitle:@"管理" forState:UIControlStateNormal];
    [self.editButton addTarget:self action:@selector(doManageItemEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.editButton];
    
    self.title = @"我的影片";
}

- (void)backHome:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Film Collection View
- (void)initFilmCollectionView {
    static NSString* filmCellIdentifier = @"NvFilmCollectionViewCell";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.filmCollectionView registerNib:[UINib nibWithNibName:@"NvFilmCollectionViewCell" bundle:myBundle]  forCellWithReuseIdentifier:filmCellIdentifier];
}

#pragma mark - Utility Methods

- (NvFilmCollectionViewCell *)cellAtIndexPath:(NSIndexPath *)indexPath {
    return (NvFilmCollectionViewCell*)[self.filmCollectionView cellForItemAtIndexPath:indexPath];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.sourceData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* filmCellIdentifier = @"NvFilmCollectionViewCell";
    NvFilmCollectionViewCell* filmCell = [self.filmCollectionView dequeueReusableCellWithReuseIdentifier:filmCellIdentifier forIndexPath:indexPath];
    MsVideoUploadModel *model = self.sourceData[indexPath.item];
    CGFloat wid = filmCell.width_LL;
    CGFloat hgt = filmCell.height_LL;
    if (model.scale == NvSSVideoCreateScaleHorizontal) {
        filmCell.leftLayerConstraint.constant = 0;
    } else {
        filmCell.leftLayerConstraint.constant = (wid - hgt*0.7-13)/2;
    }
    filmCell.durationLabel.text = model.fileDuration;
    filmCell.videoLabel.text = model.fileName;
    filmCell.videoCoverImageView.image = model.corverImage;
    filmCell.filmSizeLabel.text = [NSString stringWithFormat:@"%.1fM",model.fileSize];
    filmCell.model = model;
    return filmCell;
}


#pragma mark - UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isEditing) {
        MsVideoUploadModel *model = [self.sourceData objectAtIndex:indexPath.item];
        model.isSelected = !model.isSelected;
        [self.filmCollectionView reloadData];
        [self updateAllSelectedButtonState];
        [self updateCancleButtonState];
    }else {
        MsVideoUploadModel *model = [self.sourceData objectAtIndex:indexPath.item];
        NvFilmUploadViewController *filmUploadViewController = [[NvFilmUploadViewController alloc] init];
        filmUploadViewController.uploadModel = model;
        [self.navigationController pushViewController:filmUploadViewController animated:YES];
    }
}

//collectionView Layout

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewFlowLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.filmCollectionView.frame.size.width - 6)/2,
                      (self.filmCollectionView.frame.size.width - 6)*0.71/2 + 20);
}

#pragma mark - FilmEditButtonAbout
- (void)doManageItemEvent:(UIButton *)sender {
    self.isEditing = !self.isEditing;
    [self updateButtonStateWith:self.isEditing];
}

- (void)updateBottomView {
    if (self.sourceData.count <= 0) {
        [self.editButton setTitle:@"管理" forState:UIControlStateNormal];
        self.editButton.userInteractionEnabled = NO;
        [self.bottomView setHidden:YES];
    }
}

- (void)updateButtonStateWith:(BOOL)isClick {
    if (isClick) {
        [self.bottomView setHidden:NO];
        [self.editButton setTitle:@"取消" forState:UIControlStateNormal];
        [self updateAllSelectedButtonState];
    } else {
        [self.bottomView setHidden:YES];
        [self.editButton setTitle:@"管理" forState:UIControlStateNormal];
        for (MsVideoUploadModel *model in self.sourceData) {
            model.isSelected = NO;
        }
        [self updateCancleButtonState];
        [self updateAllSelectedButtonState];
    }
    [self.filmCollectionView reloadData];
}

- (void)updateAllSelectedButtonState {
    UIButton *sender = [self.bottomView viewWithTag:1111];
    if (self.sourceData.count <= 0) {
        [sender setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        return;
    }
    BOOL isAll = YES;
    for (MsVideoUploadModel *model in self.sourceData) {
        if (!model.isSelected) {
            isAll = NO;
            break;
        }
    }
    if (isAll) {
        [sender setTitle:@"取消全选" forState:UIControlStateNormal];
    } else {
        [sender setTitle:@"全选" forState:UIControlStateNormal];
    }
}

- (void)updateCancleButtonState {
    UIButton *sender = [self.bottomView viewWithTag:2222];
    BOOL canUse = NO;
    for (MsVideoUploadModel *model in self.sourceData) {
        if (model.isSelected) {
            canUse = YES;
            break;
        }
    }
    sender.userInteractionEnabled = canUse;
    if (canUse) {
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    } else {
        [sender setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
}

- (void)doAllSelectedEvent:(UIButton *)sender {
    if (self.sourceData.count == 0) {
        return;
    }
    if ([sender.titleLabel.text isEqualToString:@"全选"]) {
        for (MsVideoUploadModel *model in self.sourceData) {
            model.isSelected = YES;
        }
        [sender setTitle:@"取消全选" forState:UIControlStateNormal];
    } else {
        for (MsVideoUploadModel *model in self.sourceData) {
            model.isSelected = NO;
        }
        [sender setTitle:@"全选" forState:UIControlStateNormal];
    }
    [self.filmCollectionView reloadData];
    [self updateCancleButtonState];
}

- (void)doDeleteBtnEvent:(UIButton *)sender {
    [Utils showConfirmAlertWithTitle:@"删除提示" message:@"是否删除,不可恢复" yesTitle:@"确定" yesAction:^{
        [self deleteSelectedModel];
    } cancelTitle:@"取消" cancelAction:nil];
}
- (void)deleteSelectedModel {
    NSMutableArray *deleteArray = [self.sourceData mutableCopy];
    for (MsVideoUploadModel *curModel in deleteArray) {
        if (curModel.isSelected) {
            [self.sourceData removeObject:curModel];
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.filmCollectionView reloadData];
        [self updateAllSelectedButtonState];
        [self updateCancleButtonState];
        [self updateBottomView];
    });
}

- (BOOL)hasVideoInLocalWith:(NSURL *)modelURL {
    __block BOOL hasFound = NO;
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    for (PHAsset *asset in self.allLocalVides) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            if ([urlAsset.URL isEqual:modelURL]) {
                hasFound = YES;
            }
            dispatch_semaphore_signal(sem);
        }];
        //等待信号
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    }
    return hasFound;
}

- (PHAsset *)searchCurVideoWith:(NSURL *)modelURL {
    for (PHAsset *asset in self.allLocalVides) {
        if ([self hasVideoInLocalWith:modelURL]) {
            return asset;
        }
    }
    return nil;
}

- (PHAssetCollection *)createdAssetCollection {
    // 从已存在相簿中查找这个应用对应的相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:NS_COMPILED_VIDEO_ASSETS_GROUP_NAME]) {
            return assetCollection;
        }
    }
    // 没有找到对应的相簿, 得创建新的相簿
    // 错误信息
    NSError *error = nil;
    // PHAssetCollection的标识, 利用这个标识可以找到对应的PHAssetCollection对象(相簿对象)
    __block NSString *assetCollectionLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 创建相簿的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:NS_COMPILED_VIDEO_ASSETS_GROUP_NAME].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    
    // 如果有错误信息
    if (error) return nil;
    // 获得刚才创建的相簿
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

- (void)initLocalVideoData {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            PHAssetCollection *assetCollection = [self createdAssetCollection];
            // 是否按创建时间排序
            PHFetchOptions *option = [[PHFetchOptions alloc] init];
            option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeVideo];
            option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
            // 获取所有视频对象
            PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
            self.allLocalVides = fetchResult;
        }
    }];
    
}

- (void)writeDataToFile {
    NSMutableArray *finishData = [NSMutableArray array];
    for (MsVideoUploadModel *model in self.sourceData) {
        NSDictionary *dict = [model changeToDictionary];
        [finishData addObject:dict];
    }
    NSString *filename = [self videoInfoFileName];
    [finishData writeToFile:filename atomically:YES];
}

- (NSString *)videoInfoFileName {
    NSString *assetPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //得到完整的文件名
    return [assetPath stringByAppendingPathComponent:@"MsLocalVideoInfo.plist"];
}
@end
